<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/2
 * Time: 13:58
 */
namespace App\Services;

use App\Repositories\OrderRepository;
use App\Repositories\PlatformProfitRepository;
use App\Repositories\RepaymentPlanConsumeRepository;
use App\Repositories\RepaymentPlanRepaymentRepository;
use App\Repositories\RepaymentPlanRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserLevelPassageRepository;
use App\Repositories\UserLevelRelationsRepository;
use App\Repositories\UserLevelRepository;
use App\Repositories\UserProfitRepository;
use App\Repositories\UserRepository;
use App\Services\Pay\AlipayService;
use App\Services\Pay\WxpayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayLevelProfitService
{
    protected $userLevelRelationsRepository;
    protected $userLevelRelationsService;
    protected $userLevelRepository;
    protected $userProfitRepository;
    protected $platformProfitRepository;
    protected $userRepository;
    protected $orderRepository;
    protected $threeApiErrorLogsRepository;
    protected $messageService;

    public function __construct(
                                UserLevelRelationsRepository $userLevelRelationsRepository,
                                UserLevelRelationsService $userLevelRelationsService,
                                UserLevelRepository $userLevelRepository,
                                UserProfitRepository $userProfitRepository,
                                PlatformProfitRepository $platformProfitRepository,
                                UserRepository $userRepository,
                                UserProfitService $userProfitService,
                                OrderRepository $orderRepository,
                                ThreeApiErrorLogsRepository $threeApiErrorLogsRepository,
                                MessageService $messageService)
    {
        $this->userLevelRelationsRepository = $userLevelRelationsRepository;
        $this->userLevelRelationsService = $userLevelRelationsService;
        $this->userLevelRepository = $userLevelRepository;
        $this->userProfitRepository = $userProfitRepository;
        $this->platformProfitRepository = $platformProfitRepository;
        $this->userRepository = $userRepository;
        $this->userProfitService = $userProfitService;
        $this->orderRepository = $orderRepository;
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
        $this->messageService = $messageService;
    }

    /**
     * 微信支付回调
     */
    public function wxpayNotify()
    {
        $postStr = file_get_contents('php://input');
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        Log::info('wxpay==' . json_encode($postObj));
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $notifySign = $postObj->sign;
        $postArr = (array)$postObj;
        unset($postArr['sign']);
        $mchid = config('pay.wxpay.mchid');
        $appid = config('pay.wxpay.appid');
        $appKey = config('pay.wxpay.app_key');
        $apiKey = config('pay.wxpay.api_key');
        $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey);
        if ($wxPay::getSign($postArr, $apiKey) != $notifySign) {
            Log::error('微信支付回调验证签名错误');
            die('wxpay sign error');
        }
        //支付成功
        //开启事务
        DB::beginTransaction();
        try {
            //更新订单状态成功
            $this->orderRepository->updateOrderStatusByOrderNo($postObj->out_trade_no, 6002);
            $order = $this->orderRepository->byOrderNo($postObj->out_trade_no);
            $this->userRepository->updateUserLevel($order->user_id, $order->goods_id);//升级为代言人
            $this->userLevelRelationsRepository->updateUserLevelId($order->user_id, $order->goods_id);//关系等级也升级为代言人
            $this->levelProfit($order->pay_amount, $order->order_no, $order->user_id, $order->goods_id);//会员升级收益
            DB::commit();
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('wxpay_db_error=='. json_encode($e));
        }
        $errorRes = [
            'order_no' => $postObj->out_trade_no,
            'error_code' => $postObj->return_code,
            'error_msg' => json_encode($postObj),
            'api_type' => 15
        ];
        $this->threeApiErrorLogsRepository->create($errorRes);
    }

    /**
     * 支付宝回调
     * 程序执行完后必须打印输出“success”（不包含引号）。如果商户反馈给支付宝的字符不是success这7个字符，支付宝服务器会不断重发通知，
     * 直到超过24小时22分钟。一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）
     * {"gmt_create":"2018-09-08 11:33:12","charset":"utf8","seller_email":"3535495619@qq.com","subject":"\u5f00\u901a\u9f99\u732b\u7ba1\u5bb6-\u4ee3\u8a00\u4eba","sign":"bRssgh1vTg3KA7m0y14RkE3F\/XIIccKo41GRMdxwhCMa3GXQqy0KhX30R88sC+0T1u7h7Fx3o2KSEivxy6FMoalC\/HelaeOAknHofBJ+vRwDptobBWbyDLhTt5A5Rek6zALq5SMIIXzeI3DYJ9jhuZgkvF0Fo88h2oaVStDdIPPxSIHRJCEJZFK8GkaPo3yRwnQgPcUXyX8tRDHFGUBMRFpx5k90T7OwrYTgOdi+ppdmItpAe1oegHUjrO3BAAkTH0+ZwFX1yL2Oa+HLqJ2eudjbyhe3McW7LanSgrjMP2WIf\/cuIcHe8HBPhoGp3quqCycpalYGiFEQoAHkDHgfAQ==","buyer_id":"2088202274797550","invoice_amount":"0.01","notify_id":"2018090800222113312097550519360715","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","app_id":"2018080460961100","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088231185166942","gmt_payment":"2018-09-08 11:33:12","notify_time":"2018-09-08 11:33:13","version":"1.0","out_trade_no":"A908775726865922","total_amount":"0.01","trade_no":"2018090822001497550531612994","auth_app_id":"2018080460961100","buyer_logon_id":"281***@qq.com","point_amount":"0.00"}
     */
    public function alipayNotify(Request $request)
    {
        Log::info('alipay==' . json_encode($request->all()));
        $aliPay = new AlipayService();
        $aliPay->alipayPublicKey(config('pay.alipay.rsa_public_key'));
        //验证签名
        $result = $aliPay->rsaCheck($request->all());
        if ($result) {
            //支付完成
            if ($request->trade_status == 'TRADE_FINISHED') {
                echo 'success';
            }
            //支付成功
            if ($request->trade_status == 'TRADE_SUCCESS') {
                //开启事务
                DB::beginTransaction();
                try {
                    //更新订单状态成功
                    $this->orderRepository->updateOrderStatusByOrderNo($request->out_trade_no, 6002);
                    $order = $this->orderRepository->byOrderNo($request->out_trade_no);
                    $this->userRepository->updateUserLevel($order->user_id, $order->goods_id);//升级为代言人
                    $this->userLevelRelationsRepository->updateUserLevelId($order->user_id, $order->goods_id);//关系等级也升级为代言人
                    $this->levelProfit($order->pay_amount, $order->order_no, $order->user_id, $order->goods_id);//会员升级收益
                    DB::commit();
                    echo 'success';
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::info('alipay_db_error=='. json_encode($e));
                }
            }
        } else {
            echo 'error';
        }
        $errorRes = [
            'order_no' => $request->out_trade_no,
            'error_code' => $request->trade_status,
            'error_msg' => json_encode($request->all()),
            'api_type' => 13
        ];
        $this->threeApiErrorLogsRepository->create($errorRes);
    }

    /**
     * 只有代言人或服务商有收益
     * 直属代言人0.65 从属代言人0.25
     * 直属服务商0.85 从属服务商0.30
     * 当级分润金额 = 还款金额 * （当级使用费率 - 当级结算费率）* 当级分润比例
     */
    public function levelProfit($money, $orderNo, $fromUserId, $goodsId)
    {
        if ($goodsId == 2) {
            $messageTemplatedId = 11;
        } else {
            $messageTemplatedId = 10;
        }
        $userOwn = $this->userRepository->byId($fromUserId);
        //判断上一级是否需要升级为高级会员
//        $currentUserLevelRelations = $this->userLevelRelationsRepository->first($fromUserId);
//        //上一级是否为普通
//        $upLevel = $this->userLevelRelationsRepository->first($currentUserLevelRelations->pid);
//        if (!empty($upLevel) && $upLevel->level_id > 3) {
//            $this->userLevelRelationsRepository->updateUserLevelId($upLevel->user_id, 3);
//            $this->userRepository->updateUserLevel($upLevel->user_id, 3);
//        }
        //找出上两级会员
        $userLevelRelationsService = $this->userLevelRelationsService->getUserLevelRelations($fromUserId);
        if (!empty($userLevelRelationsService)) {
            //直接收益
            if (!empty($userLevelRelationsService['two'])) {
                if ($userLevelRelationsService['two']['level_id'] <= 2) {
                    $directProfit = $this->userProfitService->userProfit($userLevelRelationsService['two']['level_id'], $money, 0,
                        1, 0, '', $userOwn->mobile, $orderNo, $money, $fromUserId,
                        $userLevelRelationsService['two']['user_id'], $messageTemplatedId, 0);
                    $directToUserId = $userLevelRelationsService['two']['user_id'];
                } else {
                    $directProfit = 0;
                    $directToUserId = 0;
                }
            } else {
                $directProfit = 0;
                $directToUserId = 0;
            }
            //间接收益
            if (!empty($userLevelRelationsService['one'])) {
                if ($userLevelRelationsService['one']['level_id'] <= 2) {
                    $indirectProfit = $this->userProfitService->userProfit($userLevelRelationsService['one']['level_id'], $money, 0,
                        1, 0, '', $userOwn->mobile, $orderNo, $money, $fromUserId,
                        $userLevelRelationsService['one']['user_id'], $messageTemplatedId, 1);
                    $indirectToUserId = $userLevelRelationsService['one']['user_id'];
                } else {
                    $indirectProfit = 0;
                    $indirectToUserId = 0;
                }
            } else {
                $indirectProfit = 0;
                $indirectToUserId = 0;
            }
            //平台收益
            $platformProfit = $money - $directProfit - $indirectProfit;
            $data = [
                'bill_no' => makeOrderNo(),
                'from_profit_sn' => $orderNo,
                'revenue_money' => $money,
                'profit_money' => $platformProfit,
                'from_user_id' => $fromUserId,
                'direct_to_user_id' => $directToUserId,
                'direct_profit_money' => $directProfit,
                'indirect_to_user_id' => $indirectToUserId,
                'indirect_profit_money' => $indirectProfit,
                'profit_type' => 1,//收益类型： 1好友升级 2好友还款 3好友收款 4交易返现 5办理贷款 6办信用卡
                'create_time' => time(),
                'create_month' => date('Y-m'),
            ];
            $this->platformProfitRepository->create($data);
        }
    }
}